package com.seckill.controller;

import com.seckill.common.CommonResponse;
import com.seckill.common.error.BusinessError;
import com.seckill.common.error.BusinessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Controller基类
 */
public class BaseController {
    public static final String CONTENT_TYPE_FORMED="application/x-www-form-urlencoded";

    /**
     * 如果异常未被处理，当异常会被抛到tomcat的容器层，而tomcat的处理只能是返回500的错误页。
     * 我们定义exceptionHandler来解决未被controller层吸收的异常。
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CommonResponse handlerException(HttpServletRequest request, Exception e) {
        Map<String,Object> responseData = new HashMap<>();
        if(e instanceof BusinessException){
            BusinessException businessException = (BusinessException) e;
            responseData.put("errorCode", businessException.getErrorCode());
            responseData.put("errorMsg",businessException.getErrorMsg());
        }else {
            responseData.put("errorCode", BusinessError.UNKNOWN_ERROR.getErrorCode());
            responseData.put("errorMsg",BusinessError.UNKNOWN_ERROR.getErrorMsg());
        }
        return CommonResponse.create(responseData,"fail");
    }
}
